//
//  addJobVC.m
//  HappyStore
//
//  Created by 陈锋 on 16/6/8.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "addJobVC.h"
#import "eduDatePickView.h"
#import "SelectedAddress.h"
@interface addJobVC ()<selectedDateDelegate1,UIActionSheetDelegate,selectedAddressDelegate,UIGestureRecognizerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    BOOL selectStartAndEndDate;
    NSString *strEndDate;
    UIImage *imgSelected;
}
@property (weak, nonatomic) IBOutlet UITextField *addressTX;
@property (weak, nonatomic) IBOutlet UILabel *isLabel;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
@property (weak, nonatomic) IBOutlet UIButton *endBtn;
@property (weak, nonatomic) IBOutlet UITextField *posiNameTX;
@property (weak, nonatomic) IBOutlet UITextField *comNameTX;
@property (weak, nonatomic) IBOutlet UIButton *logoBtn;
@property (weak, nonatomic) IBOutlet UIImageView *headImg;
@property (weak, nonatomic) IBOutlet UISwitch *isflag;
@property (strong ,nonatomic)UILabel *tip;
@property (strong, nonatomic)UILabel *count;

@end

@implementation addJobVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.titleStr;
    
    if ([self.titleStr isEqualToString:@"教育经历"]) {
        self.posiNameTX.placeholder = @"学校名称";
        self.comNameTX.placeholder = @"专业名称";
        self.addressTX.placeholder = @"学校地址";
        self.isLabel.text = @"在读";
        [self.startBtn setTitle:@"入学时间" forState:0];
        self.headImg.image = [UIImage imageNamed:@"btn_myD_addSchool"];
        
    }else{

        self.headImg.image = [UIImage imageNamed:@"btn_myD_addCompay"];
    }
    
    if ([self.isflag isOn]) {
        [self.endBtn setTitle:@"至今" forState:0];
        self.endBtn.userInteractionEnabled = NO;
    }
    
    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"Back" highImage:@"Back"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIButton * commentBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44.0f, 44.0f)];
    commentBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [commentBtn setTitle:@"  保存" forState:UIControlStateNormal];
    [commentBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [commentBtn addTarget:self action:@selector(rightBarButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightBtn = [[UIBarButtonItem alloc]initWithCustomView:commentBtn];
    self.navigationItem.rightBarButtonItem = rightBtn;
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}
-(void)rightBarButtonItemClick{
    
    //token=rE3F2m8AvfC7CVh85O9q&userId=用户id&time=2010.09-2015.06&workName=公司名称&workPositionName=担任职位 参数说明：photo-为图片
    if (imgSelected && self.addressTX.text.length > 1 && self.comNameTX.text.length > 1 && self.posiNameTX.text.length > 1 && self.startBtn.titleLabel.text.length > 4 && self.endBtn.titleLabel.text.length > 1) {
        
        if ([self.titleStr isEqualToString:@"教育经历"]) {
            //token=rE3F2m8AvfC7CVh85O9q&userId=用户id&time=2010.09-2015.06&schoolName=学校名称&schoolStudy=专业名称 参数说明：photo-为图片
            [self showRoundProgressWithTitle:@"加载中..."];
            
            NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
            [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
            [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
            NSString *strTime = [NSString stringWithFormat:@"%@-%@",self.startBtn.titleLabel.text,self.endBtn.titleLabel.text];
            [muDicParameters setObject:strTime forKey:@"time"];
            [muDicParameters setObject:self.posiNameTX.text forKey:@"schoolName"];
            [muDicParameters setObject:self.comNameTX.text forKey:@"schoolStudy"];
            
            NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"addPeopleEducation_app_myHome.im.lensum"];
            
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            
            [manager POST:strURl parameters:muDicParameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                NSData *imageData = UIImageJPEGRepresentation(imgSelected, 0.5);
                [formData appendPartWithFileData:imageData name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"];

            } progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
//                NSLog(@"%@",dicInfo);
                if ([dicInfo[@"result"] integerValue] == 1) {
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    [self showRightWithTitle:dicInfo[@"msg"] autoCloseTime:2];
                }else {

                    [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
                }

            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [self showSingleIconBubble:error.localizedDescription];

            }];
        }else{
        
            [self showRoundProgressWithTitle:@"请稍后..."];
        NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
        NSString *strTime = [NSString stringWithFormat:@"%@-%@",self.startBtn.titleLabel.text,self.endBtn.titleLabel.text];
        [muDicParameters setObject:strTime forKey:@"time"];
        [muDicParameters setObject:self.posiNameTX.text forKey:@"workName"];
        [muDicParameters setObject:self.comNameTX.text forKey:@"workPositionName"];
        
        NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"addPeopleWork_app_myHome.im.lensum"];
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        [manager POST:strURl parameters:muDicParameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            NSData *imageData = UIImageJPEGRepresentation(imgSelected, 0.5);
            [formData appendPartWithFileData:imageData name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
//            NSLog(@"%@",dicInfo);

            if ([dicInfo[@"result"] integerValue] == 1) {
                
                [self.navigationController popViewControllerAnimated:YES];
                [self showRightWithTitle:dicInfo[@"msg"] autoCloseTime:2];
                
            }else {

                [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
            }

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

           [self showSingleIconBubble:error.localizedDescription];

        }];
    }
        
    }else{

        [self showSingleIconBubble:@"请完善资料"];
    }



}
-(void)leftBarButtonItemClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}


// 工作地点
- (IBAction)addressBtn:(UIButton *)sender {
    
    SelectedAddress *selectAddress = [SelectedAddress sharedSelectedAddress];
    selectAddress.delegatee = self;
    [selectAddress btnClickAddress];
}

// 开始时间
- (IBAction)startTime:(UIButton *)sender {
    selectStartAndEndDate = YES;
    eduDatePickView *datt = [eduDatePickView sharedSelectedAddress];
    datt.delegatee = self;
    [datt btnClickDate];
}

// 结束时间
- (IBAction)endTime:(id)sender {
    selectStartAndEndDate = NO;
    eduDatePickView *datt = [eduDatePickView sharedSelectedAddress];
    datt.delegatee = self;
    [datt btnClickDate];
}

// logo
- (IBAction)addLogo:(UIButton *)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"照片选择"
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"相机",@"相册", nil];
    [actionSheet showInView:self.view];
    
}
#pragma mark - 选择照片
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
    pickerImage.delegate = self;
    pickerImage.allowsEditing = YES;//设置可编辑
    switch (buttonIndex) {
        case 0:
        {
            NSLog(@"相机");
            pickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:pickerImage animated:YES completion:nil];//进入照相界面
        }
            break;
        case 1:
        {
            NSLog(@"相册");
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //图片库
            [self presentViewController:pickerImage animated:YES completion:nil];//进入照相界面
        }
            break;
        case 2:
        {
            NSLog(@"取消");
        }
            break;
    }
    
}
//点击相册中的图片 货照相机照完后点击use  后触发的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    imgSelected = image;
    self.headImg.image = imgSelected;
    [self.headImg.layer setCornerRadius:(self.logoBtn.frame.size.height/2)];
    [self.headImg.layer setMasksToBounds:YES];
    [self.headImg setContentMode:UIViewContentModeScaleAspectFill];
    [self.headImg setClipsToBounds:YES];
    self.headImg.layer.shadowColor = [UIColor whiteColor].CGColor;
    self.headImg.layer.shadowOffset = CGSizeMake(4, 4);
    self.headImg.layer.shadowOpacity = 0.5;
    self.headImg.layer.shadowRadius = 2.0;
}

//点击cancel 调用的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
}
- (void)seceltedDate:(NSString *)date
{
    if (selectStartAndEndDate) {
//        strStartDate = date;
        [self.startBtn setTitle:date forState:0];
        [self.startBtn setTitleColor:[UIColor colorWithRed:137/255.0f green:137/255.0f blue:137/255.0f alpha:1.0f] forState:0];

    }else {
//        strEndDate = date;
        [self.endBtn setTitle:date forState:0];
        [self.endBtn setTitleColor:[UIColor colorWithRed:137/255.0f green:137/255.0f blue:137/255.0f alpha:1.0f] forState:0];

    }
}
#pragma mark - 所在地代理
- (void)seceltedRowSshowMsg:(NSString *)showMsg andProvince:(NSString *)strProvince andCity:(NSString *)strCity andDistrict:(NSString *)strDistrict
{
    self.addressTX.text = showMsg;
}
// 开关
- (IBAction)flagBtn:(UISwitch *)sender {
    
    UISwitch *switchButton = (UISwitch*)sender;
    BOOL isButtonOn = [switchButton isOn];
    if (isButtonOn) {//开
        if ([self.titleStr isEqualToString:@"教育经历"]){
            self.isLabel.text = @"在读";
        }else{
        self.isLabel.text = @"在职";
        }
        [self.endBtn setTitle:@"至今" forState:0];
        self.endBtn.userInteractionEnabled = NO;
    }else {//关
        if ([self.titleStr isEqualToString:@"教育经历"]){
            self.isLabel.text = @"毕业";
            [self.endBtn setTitle:@"毕业时间" forState:0];
        }else{
            self.isLabel.text = @"离职";
            [self.endBtn setTitle:@"离职时间" forState:0];
        }
        
        self.endBtn.userInteractionEnabled = YES;
    }
    
}


@end
